﻿using Account;
using Account.Input;
using Account.Output;
using Bridge.Shared.Enums.IdentityService;
using Bridge.Shared.Helper;
using Bridge.Shared.Models;
using IdentityModel.Client;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Identity;
using static System.Runtime.InteropServices.JavaScript.JSType;



public class UserAccountService : ApplicationService, IUserAccountService
{
    private readonly IConfiguration _config;
    private readonly IRepository<IdentityUser> _userRepository;
    public UserAccountService(IConfiguration config, IRepository<IdentityUser> userRepository)
    {
        _config = config;
        _userRepository = userRepository;
    }
    /// <summary>
    /// 登录
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<ResponseResult<LoginOutput>> SSOLogin(LoginInput input)
    {
        //查询用户名是否存在
        IdentityUser user = await _userRepository.FirstOrDefaultAsync(s => s.UserName == input.UserName.Trim());
        if (user == null)
        {
            return ResponseResult<LoginOutput>.Fail("用户名不存在！");
        }

        var client = new HttpClient();
        //var clientScope = string.Join(" ", _serviceScope);
        var parameters = new Parameters();
        parameters.Add("username", input.UserName);
        parameters.Add("client_key", input.ClientAuthKey);
        var tokenResponse = await client.RequestTokenAsync(new TokenRequest
        {
            Address = $"{_config["AuthServer:Authority"]}/connect/token",
            ClientId = "myClient",
            ClientSecret = "1q2w3e*",
            GrantType = "username",

            Parameters = parameters,
        });

        LoginOutput loginOutput = new LoginOutput()
        {
            LoginResult = LoginResultEnum.Success,
            Token = tokenResponse.AccessToken,
            RefreshToken = tokenResponse.RefreshToken,
            UserName = user.UserName
        };
        return ResponseResult<LoginOutput>.Success("登录成功", loginOutput);

    }
    /// <summary>
    /// 登录
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<ResponseResult<LoginOutput>> Login(LoginInput input)
    {
        try
        {

            //查询用户名是否存在
            IdentityUser user = await _userRepository.FirstOrDefaultAsync(s => s.UserName == input.UserName.Trim());
            if (user == null)
            {
                return ResponseResult<LoginOutput>.Fail("用户名不存在！");
            }
            //1.去认证服务器验证用户名密码是否正确 
            UserLoginInfo login = new UserLoginInfo()
            {
                UserNameOrEmailAddress = user.UserName,
                Password = input.Password,
                RememberMe = false
            };

            var jsonRequest = JsonConvert.SerializeObject(login);
            var accountResult = HttpRequestHelper.PostUrl($"{_config["AuthServer:Authority"]}/api/account/login", jsonRequest);
            var data = JsonConvert.DeserializeObject<AccountResponseOutput>(accountResult);

            if (data == null || data.Result != LoginResultTypeEnum.Success)
            {
                return ResponseResult<LoginOutput>.Fail("用户名或密码错误！");
            }

            //获取token
            var tokenResponse = await GetAccessToken(user.UserName, input.Password);
            LoginOutput loginOutput = new LoginOutput()
            {
                LoginResult = LoginResultEnum.Success,
                Token = tokenResponse.AccessToken,
                RefreshToken = tokenResponse.RefreshToken,
                UserName = user.UserName
            };
            return ResponseResult<LoginOutput>.Success("登录成功", loginOutput);
        }
        catch (Exception ex)
        {

            return ResponseResult<LoginOutput>.Fail($"登录失败，原因：{ex.Message}");
        }

    }

    /// <summary>
    /// 获取token
    /// </summary>
    /// <param name="userName"></param>
    /// <param name="passWord"></param>
    /// <returns></returns>
    private async Task<TokenResponse> GetAccessToken(string userName, string passWord)
    {
        var client = new HttpClient();
        //var clientScope = string.Join(" ", _serviceScope);
        var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
        {
            Address = $"{_config["AuthServer:Authority"]}/connect/token",
            ClientId = "console-client-demo",
            ClientSecret = "1q2w3e*",
            GrantType = "password",
            UserName = userName,
            Password = passWord,
            //Scope = "IdentityService BaseService"
           // Scope = "IdentityServer"
        });
        return tokenResponse;
    }

    public async Task<ResponseResult> LoginOut()
    {
        //清空单前用户的缓存信息
        var user = CurrentUser;
        if(user == null)
        {
            return ResponseResult.Fail("用户未登录！");
        }


        return ResponseResult.Success("操作成功！");
    }

    public async Task<ResponseResult<LoginOutput>> PhoneLogin([FromBody] PhoneLoginInput login)
    {
        //查询用户名是否存在
        IdentityUser user = await _userRepository.FirstOrDefaultAsync(s => s.UserName == login.PhoneNumber.Trim() || s.PhoneNumber==login.PhoneNumber.Trim());
        if (user == null)
        {
            return ResponseResult<LoginOutput>.Fail("用户名不存在！");
        }

        var client = new HttpClient();
        //var clientScope = string.Join(" ", _serviceScope);
        var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
        {
            Address = $"{_config["AuthServer:Authority"]}/connect/token",
            ClientId = "myClient",
            ClientSecret = "1q2w3e*",
            GrantType = "username",
            UserName = user.UserName,
            //Scope = "IdentityServer"
        });


        LoginOutput loginOutput = new LoginOutput()
        {
            LoginResult = LoginResultEnum.Success,
            Token = tokenResponse.AccessToken,
            RefreshToken = tokenResponse.RefreshToken,
            UserName = user.UserName
        };
        return ResponseResult<LoginOutput>.Success("登录成功", loginOutput);
    }
    

}

